package org.gitman.agentplatform.agent.impl.isolated;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

import org.gitman.agentplatform.agent.api.AgentInfo;
import org.gitman.agentplatform.agent.api.AgentPlan;
import org.gitman.agentplatform.agent.api.utils.AbstractAgent;
import org.gitman.agentplatform.model.utils.GraphTools;

public class IsolatedNotWaitingAgent extends AbstractAgent{
	Stack<Integer> shorthestPath =null;

	@Override
	public Integer getStep(Collection<AgentInfo> agentsInRange) {
		updatePlan(agentsInRange);
		if(shorthestPath.size() > 0){
			return shorthestPath.peek();
		}else{
			return null;
		}
	}
	@Override
	public AgentPlan getPlan(int depth, Collection<AgentInfo> agentsInRange) {
		updatePlan(agentsInRange);
		int size = shorthestPath.size() < depth ? shorthestPath.size() : depth;
		Stack<Integer> copy = (Stack<Integer>) shorthestPath.clone();
		Integer [] tab = new Integer[size];
		for(int i=0;i<size;i++){
			tab[i] = copy.pop();
		}
		HashMap<Integer[],Double> map = new HashMap<Integer[], Double>();
		map.put(tab, 1.0);
		return new AgentPlan(map);
	}
	private void updatePlan(Collection<AgentInfo> agents) {
		Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>();
		Set<Integer> list = new HashSet<Integer>();
		for(AgentInfo info : agents){
			list.add(info.getCurrentVertexID());
		}
		map.put(1, list);
		shorthestPath = GraphTools.getShorthestPath(graph, agentInfo.getCurrentVertexID(), agentInfo.getEndVertexID(),map);
		if(shorthestPath == null){
			shorthestPath = new Stack<Integer>();
		}
		while(shorthestPath.size() > 0 && agentInfo.getCurrentVertexID().equals(shorthestPath.peek())){
			shorthestPath.pop();
		}
	}
}
